﻿using System;
using System.IO;

namespace Netfraction.Common.DataStorage
{
	public class BinaryDataStore : DataStore, IDataStore
	{
		/// <summary>
		/// Creates a new TextDataStore instance.
		/// </summary>
		/// <param name="owner"></param>
		public BinaryDataStore(DataSource owner)
			: base(owner)
		{
			this.DataStoreType = DataStoreType.BinaryFile;
		}

		/// <summary>
		/// Creates a new BinaryDataStore instance and the specified data store. Does not overwrite an existing store.
		/// </summary>
		/// <param name="owner"></param>
		/// <param name="storeName"></param>
		public BinaryDataStore(DataSource owner, string storeName)
			: base(owner)
		{
			this.DataStoreType = DataStoreType.BinaryFile;
			this.DataStoreName = storeName;

			Create(storeName, false);
		}

		public bool Create(string name, bool overwrite)
		{
			if (!CheckBasePath(name))
				return false;

			if (!overwrite && File.Exists(Path.Combine(this.BasePath, name)))
				return true;

			if (!Directory.Exists(Path.GetDirectoryName(Path.Combine(this.BasePath, name))))
				Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(this.BasePath, name)));

			this.DataStoreName = name;

			return true;
		}

		public bool Delete()
		{
			if (this.DataStoreName == string.Empty)
				return false;

			File.Delete(this.FullPath);

			return File.Exists(this.FullPath);
		}
	}
}
